package com.koron.plan.web.repairplan.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.query.PageQuery;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.workflow.RedirectQuery;
import com.koron.bean.workflow.SubmitterParam;
import com.koron.bean.workflow.WorkflowController;
import com.koron.bean.workflow.WorkflowUser;
import com.koron.common.core.annocation.CasUser;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.interceptor.OrderByInterceptor;
import com.koron.plan.web.common.CommonUtils;
import com.koron.plan.web.repairplan.bean.query.PlanPackageQuery;
import com.koron.plan.web.repairplan.bean.vo.PackageStatVO;
import com.koron.plan.web.repairplan.bean.vo.PlanPackageVO;
import com.koron.plan.web.repairplan.filter.RepairPlanPackageFilter;
import com.koron.plan.web.repairplan.service.PlanPackageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

/**
 * @author twcao
 * @title: PlanPackageController
 * @projectName GDH_EAM_V2
 * @description: 检修计划包controller
 * @date 2021/9/1310:07
 */
@Slf4j
@RestController
@Api(tags = "检修计划包")
@RequestMapping("/package")
public class PlanPackageController implements WorkflowController {

    @Autowired
    private PlanPackageService packageService;

    @Autowired
    private RepairPlanPackageFilter filter;

    @GetMapping("/selectOne")
    @ApiOperation("根据检修计划包id查询详情")
    @ApiImplicitParam(name = "id", value = "检修计划包id", required = true, dataType = "String")
    public Response<PlanPackageVO> selectOne(@CasUser @ApiIgnore EamUser user, @RequestParam String id) {
        return Response.succ(ADOConnection.runTask(user.getCurrDs(), packageService, "queryById", PlanPackageVO.class, id));
    }

    @GetMapping("/statById")
    @ApiOperation("根据检修计划包id统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "packageId", value = "检修计划包id", dataType = "String"),
            @ApiImplicitParam(name = "deptId", value = "主办单位id", dataType = "String")
    })
    public Response<PackageStatVO> statById(@CasUser @ApiIgnore EamUser user, String packageId, String deptId) {
        return Response.succ(ADOConnection.runTask(user.getCurrDs(), packageService, "statById", PackageStatVO.class, packageId, deptId));
    }

    @GetMapping("/queryList")
    @ApiOperation("检修计划包列表查询")
    public Response<PageInfo<PlanPackageVO>> queryList(@CasUser @ApiIgnore EamUser user, PlanPackageQuery query, PageQuery pageInfo) {
        OrderByInterceptor.setOrderBy(pageInfo.getOrders());
        PageHelper.startPage(pageInfo.getPage(), pageInfo.getPageSize());
        List<PlanPackageVO> list = ADOConnection.runTask(user.getCurrDs(), packageService, "queryList", List.class, query);
        return Response.succ(new PageInfo<>(list));
    }

    @PostMapping("/saveOrUpdate")
    @ApiOperation("新增/更新计划检修包")
    public Response<PlanPackageVO> saveOrUpdate(@CasUser @ApiIgnore EamUser user, @Validated @RequestBody PlanPackageVO vo, BindingResult errorMsg) {
        // 即使断言为真，仍会执行message中的表达式
        Assert.isTrue(!errorMsg.hasErrors(), errorMsg.hasErrors() ? errorMsg.getFieldErrors().get(0).getDefaultMessage() : "");
        vo.setDeptId(StringUtils.isBlank(vo.getDeptId()) ? user.getOrgId() : vo.getDeptId());
        CommonUtils.update(vo, user);
        return Response.succ(ADOConnection.runTask(user.getCurrDs(), packageService, "saveOrUpdate", PlanPackageVO.class, vo));
    }

    @DeleteMapping("/deleteById")
    @ApiOperation("删除检修计划包, 只有草稿状态的检修计划包才可以删除")
    @ApiImplicitParam(name = "packageId", value = "计划包id", required = true, dataType = "String")
    public Response<PlanPackageVO> deleteById(@CasUser @ApiIgnore EamUser user, @RequestParam String packageId) {
        return Response.succ(ADOConnection.runTask(user.getCurrDs(), packageService, "deleteById", PlanPackageVO.class, packageId));
    }

    @Override
    @ApiOperation("修改业务状态, 非前端接口")
    public Response updateState(@RequestBody RedirectQuery redirectQuery) {
        log.info("workflowUpdate = {}", JSON.toJSONString(redirectQuery));
        ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), packageService, "workflowUpdate", Boolean.class, redirectQuery);
        return Response.success();
    }

    @Override
    @ApiOperation("结束时的修改方法, 非前端接口")
    public Response updateEnd(@RequestBody RedirectQuery redirectQuery) {
        log.info("updateEnd = {}", JSON.toJSONString(redirectQuery));
        ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), packageService, "updateEnd", Boolean.class, redirectQuery);
        return Response.success();
    }

    @Override
    @ApiOperation("作废时的修改方法, 非前端接口")
    public Response updateCancel(@RequestBody RedirectQuery redirectQuery) {
        log.info("updateCancel = {}", JSON.toJSONString(redirectQuery));
        return Response.success();
    }

    /**
     * 自动过滤
     * 点击工作流提交的时候，业务需要编写此过滤器，返回过滤后的人员信息
     * @param submitterParam
     */
    @PostMapping("/{taskN}/submitter")
    public Response<List<WorkflowUser>> submitter(@PathVariable String taskN, @RequestBody SubmitterParam submitterParam) {
        log.info("检修计划包设置审批人入参: {}", JSON.toJSONString(submitterParam));
        List<WorkflowUser> users = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), filter, taskN + "Submitter", List.class, submitterParam);
        return Response.ok(users);
    }

    /**
     * 选人组件过滤
     * 点击选人组件时，业务需要编写此过滤器，返回过滤后的人员信息
     *
     * @param submitterParam
     */
    @PostMapping("/{taskN}/handler")
    public Response<List<WorkflowUser>> handler(@PathVariable String taskN, @RequestBody SubmitterParam submitterParam) {
        log.info("检修计划包选人组件过滤入参: {}", JSON.toJSONString(submitterParam));
        List<WorkflowUser> users = ADOConnection.runTask(ThreadLocalContext.get().getCurrDs(), filter,  taskN + "Handler", List.class, submitterParam);
        return Response.ok(users);
    }
}
